/**
 * Copyright (C) 2025 pony working team
 * SPDX-License-Identifier: MulanPSL-2.0
 */

/* define to prevent recursive inclusion -------------------------------------*/
#ifndef __K_MUTEX_H__
#define __K_MUTEX_H__

/* includes (standard library, system) ---------------------------------------*/
#include <stdint.h>
/* includes (other library) --------------------------------------------------*/
/* includes (project) --------------------------------------------------------*/
#include <x_list.h>
#include <x_module.h>
/* includes (local) ----------------------------------------------------------*/
#include "k_obj.h"
#include "k_task.h"

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

/* defines -------------------------------------------------------------------*/

#define ERRNO_MUTEX_ILLEGAL_ID        ERRNO_JOIN(MID_MUTEX, 1)
#define ERRNO_MUTEX_TIMEOUT           ERRNO_JOIN(MID_MUTEX, 2)
#define ERRNO_MUTEX_DELETED           ERRNO_JOIN(MID_MUTEX, 3)
#define ERRNO_MUTEX_UNAVAILABLE       ERRNO_JOIN(MID_MUTEX, 4)
#define ERRNO_MUTEX_ILLEGAL_OPERATION ERRNO_JOIN(MID_MUTEX, 5)

/* typedefs ------------------------------------------------------------------*/

typedef struct mutex {
    obj_t obj;
    uint16_t recurse;
    uint8_t prio; /* the max prio of the tasks pend on this mutex */
    task_id owner;
    dlist_t pend_q;
    dlist_t node; /* linked in task_t->owned_mutex */
} mutex_t, *mutex_id;

/* macro ---------------------------------------------------------------------*/
/* inlines -------------------------------------------------------------------*/
/* externs -------------------------------------------------------------------*/

extern int mutex_init(mutex_id m);
extern mutex_id mutex_create(void);
extern mutex_id mutex_open(const char *name, int oflag, ...);
extern int mutex_destroy(mutex_id m);
extern int mutex_timedlock(mutex_id m, unsigned int timeout);
extern int mutex_lock(mutex_id m);
extern int mutex_trylock(mutex_id m);
extern int mutex_unlock(mutex_id m);

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* __K_MUTEX_H__ */
